package com.leo.blog.web.file;

import com.leo.blog.entity.TbFile;
import com.leo.blog.entity.TbFilestr;
import com.leo.blog.service.TbFileService;
import com.leo.blog.service.TbFilestrService;
import com.leo.blog.util.FileBase64Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Classname FileController
 * @Description TODO
 * @Date 2023/4/13 13:01
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@RestController
@RequestMapping("file")
public class FileController {

    @Autowired
    private TbFileService tbFileService;

    @Autowired
    private TbFilestrService tbFilestrService;

    @GetMapping("donload")
    public void downloadController(@RequestParam("id")String id,
                                   HttpServletResponse response,
                                   @RequestHeader(name = "Range", required = false) String range) throws UnsupportedEncodingException {
        TbFile tbFile=tbFileService.getById(id);
        if(tbFile != null) {
            TbFilestr tbFilestr = tbFilestrService.getById(tbFile.getFileid());
            String fileStr = tbFilestr.getFilestr();
            byte[] bytes = FileBase64Util.base64ToBytes(fileStr);
            donload(bytes,tbFile.getFilename(),response);
        }
    }

    public void donload(byte[] data,String fileName,HttpServletResponse response){
        OutputStream outputStream=null;
        InputStream in=null;
        try {
            in=new ByteArrayInputStream(data);
            outputStream=response.getOutputStream();
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(fileName, "utf-8"));
            byte[] b = new byte[1024];
            while ((in.read(b)) != -1) {
                // 写入数据
                outputStream.write(b);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(outputStream!=null){
                try {
                    outputStream.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(in != null){
                try {
                    in.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
